package com.example.orderservice.service;

import com.example.orderservice.entity.Order;
import com.example.orderservice.feign.StockFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private StockFeignClient stockFeignClient;
    // 从Nacos配置获取订单号前缀

    @Value("${order.prefix:ORD-}")
    private String orderPrefix;

    /**
     * 创建订单
     * 流程：检查库存 -> 扣减库存 -> 创建订单
     */
    public Order createOrder(String productId, int quantity) {
        Order order = new Order();
        order.setOrderId(orderPrefix + UUID.randomUUID().toString().substring(0, 8));
        order.setProductId(productId);
        order.setQuantity(quantity);

        // 1. 检查库存
        int stock = stockFeignClient.queryStock(productId);
        if (stock < quantity) {
            order.setStatus("FAIL（库存不足）");
            return order;
        }

        // 2. 扣减库存
        boolean deductSuccess = stockFeignClient.deductStock(productId, quantity);
        if (!deductSuccess) {
            order.setStatus("FAIL（库存扣减失败）");
            return order;
        }

        // 3. 创建订单（模拟）
        order.setStatus("SUCCESS");
        return order;
    }
}